﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;

namespace NativeWiFiLibrary
{
    public class AccessPoint
    {
        public string Ssid { get; set; }
        public int PhyId { get; set; }
        public string MacAddress { get; set; }
        public BssType BssType { get; set; }
        public PhyType PhyType { get; set; }
        public int Rssi { get; set; }
        public int LinkQuality { get; set; }
        public bool InRegDomain { get; set; }
        public ushort BeaconPeriod { get; set; }
        public ulong Timestamp { get; set; }
        public ulong HostTimestamp { get; set; }
        public ushort CapabilityInformation { get; set; }
        public int CenterFrequency { get; set; }
        public double[] RateSetInMbps { get; set; }

        public object Geolocation { get; set; }

        private Network _network;

        public Network Network
        {
            get { return this._network; }
            internal set { this._network = value; }
        }

        public int Channel
        {
            get
            {
                return WlanConv.GetChannelFromFrequency(this.CenterFrequency);
            }
        }

        /// <summary>
        /// Hide constructor
        /// </summary>
        private AccessPoint() { }

        internal static AccessPoint FromWlanApi(WlanApi.WLAN_BSS_ENTRY original)
        {
            AccessPoint entry = new AccessPoint();
            entry.BeaconPeriod = original.usBeaconPeriod;
            entry.BssType = (BssType)original.dot11BssType;
            entry.CapabilityInformation = original.usCapabilityInformation;
            entry.CenterFrequency = original.ulChCenterFrequency;
            entry.HostTimestamp = original.ullHostTimestamp;
            entry.InRegDomain = original.bInRegDomain;
            entry.LinkQuality = original.uLinkQuality;

            entry.MacAddress = "";
            foreach (byte part in original.dot11Bssid)
            {
                entry.MacAddress += (entry.MacAddress.Length > 0 ? "-" : "") + (part < 16 ? "0" : "") + part.ToString("X", CultureInfo.InvariantCulture);
            }

            entry.PhyId = original.uPhyId;
            entry.PhyType = (PhyType)original.dot11BssPhyType;
            entry.Rssi = original.lRssi;
            entry.Ssid = original.dot11Ssid.SSID;
            entry.Timestamp = original.ullTimestamp;

            entry.RateSetInMbps = new double[original.wlanRateSet.uRateSetLength];
            for (int i = 0; i < entry.RateSetInMbps.Length; i++)
            {
                entry.RateSetInMbps[i] = (original.wlanRateSet.usRateSet[i] & 0x7FFF) * 0.5;
            }

            return entry;
        }
    }
}
